package weixinpay;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.httpclient.NameValuePair;
import weixinpay.util.TenpayHttpClient;

import javax.servlet.http.HttpServletRequest;

import static http_post.src.util.StringUtil.byteArrayToHexString;

/**
 * 
 * @作者：lsq
 * @时间：2015-12-29 下午12:42:56
 * 微信支付统一下单接口调用方法
 */
public class WeiXinPay {
	/** APP_ID 应用从官方网站申请到的合法appId */
	public static final String WX_APP_ID = "wx079bba8222507669";
	/** 商户号 */
	public static final String WX_PARTNER_ID = "1438430602";
	/** 统一下单接口链接 */
	public static final String url="https://api.mch.weixin.qq.com/pay/unifiedorder";
	/** 商户平台和开发平台约定的API密钥，在商户平台设置 */
	public static final String key="ZC6EGWXA2DXO2OYWWAWKKWQ729GLSYXE";

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public String submitOrder(HttpServletRequest request,int price, int tradeType, String ip,String openId,String orderCode)
			throws UnsupportedEncodingException {
		int realpayPrice = price * 100;
		List<NameValuePair> nvps = new ArrayList();
		String body="虎丘婚纱城";
		// 调用统一下单接口必需传的参数,可以查看微信支付统一下单接口api查看每个参数的意思
		nvps.add(new NameValuePair("appid", WX_APP_ID));
		nvps.add(new NameValuePair("body",  body));
		nvps.add(new NameValuePair("mch_id", WX_PARTNER_ID));
		nvps.add(new NameValuePair("nonce_str", UUID.randomUUID().toString().replace("-", "")));
		nvps.add(new NameValuePair("notify_url","http://www.kaaction.com/Admin/kdNotify")); //回调地址需要根据实际项目做修改
		nvps.add(new NameValuePair("openid", openId));
		nvps.add(new NameValuePair("out_trade_no", orderCode));
		nvps.add(new NameValuePair("spbill_create_ip", ip));//ip地址需要根据实际项目做修改
		nvps.add(new NameValuePair("total_fee", realpayPrice + ""));
		nvps.add(new NameValuePair("trade_type", "JSAPI"));
		StringBuffer sb = new StringBuffer();

		for (NameValuePair nvp : nvps) {
			sb.append(nvp.getName() + "=" + nvp.getValue() + "&");
		}

		String signA = sb.toString(); // 根据签名格式组装数据，详见微信支付api
		//System.out.println(signA);
		String stringSignTemp = signA + "key=" + key; // 根据签名格式组装数据，详见微信支付api
		//System.out.println("signA=" + signA);
		//System.out.println("stringSignTemp=" + stringSignTemp);
		String sign = DigestUtils.md5Hex(
				WeiXinPay.getContentBytes(stringSignTemp, "UTF-8")).toUpperCase();// 把组装好的签名数据md5之后字母都转换为大写，详见微信支付api
		//System.out.println("sign=" + sign);
		//request.getSession().setAttribute("sign",sign);
		nvps.add(new NameValuePair("sign", sign)); // 把签名后的数据组装成参数
		TenpayHttpClient httpClient = new TenpayHttpClient();
		httpClient.setReqContent(url);
		String resContent = "";
		String result="";
		if (httpClient.callHttpPost(url, toXml(nvps))) {
			resContent = httpClient.getResContent();
			System.out.print(resContent);
			result = new String(resContent.getBytes("UTF-8"));
			System.out.println("result=" + result);
		}
		return result;
	}
	// 转换成xml格式
	private String toXml(List<NameValuePair> params) {
		StringBuilder sb = new StringBuilder();
		sb.append("<xml>");
		for (int i = 0; i < params.size(); i++) {
			sb.append("<" + params.get(i).getName() + ">");
			sb.append("<![CDATA[");
			sb.append((params.get(i)).getValue());
			sb.append("]]>");
			sb.append("</" + params.get(i).getName() + ">");
		}
		sb.append("</xml>");
		System.out.println("xml=" + sb.toString());
		String ss =null;
		try {
			 ss =new String(sb.toString().getBytes("UTF-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return ss;
	}

	// 编码转换
	public static byte[] getContentBytes(String content, String charset) {
		if (charset == null || "".equals(charset)) {
			return content.getBytes();
		}
		try {
			return content.getBytes(charset);
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException("MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:"
					+ charset);
		}
	}

	/**
	 * 把中文转成Unicode码
	 * @param str
	 * @return
	 */
	public String chinaToUnicode(String str){
		String result="";
		for (int i = 0; i < str.length(); i++){
			int chr1 = (char) str.charAt(i);
			if(chr1>=19968&&chr1<=171941){//汉字范围 \u4e00-\u9fa5 (中文)
				result+="\\u" + Integer.toHexString(chr1);
			}else{
				result+=str.charAt(i);
			}
		}
		return result;
	}

	public static void main(String[] args) throws UnsupportedEncodingException {
		WeiXinPay wx = new WeiXinPay();
		//wx.submitOrder(10.00, 1, "127.0.0.1");
	}
}